﻿using MesTool.Model;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace MesTool
{
    public  class UserBLL
    {
        private ConnectionConfig connection = null;
        public SqlSugarClient db = null;
        public UserBLL(string sqlIp)
        {
            string SqlIP = sqlIp;
            string database = "MESDB";
            string uid = "sa";
            string pwd = "8ik,9ol.";
            connection = new ConnectionConfig()
            {
                ConnectionString = "server='" + SqlIP + "';initial catalog='" + database + "';uid='" + uid + "';pwd='" + pwd + "'",
                DbType = DbType.SqlServer,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute
            };
            db = new SqlSugarClient(connection);
        }
        /// <summary>
        /// 获取钉钉表信息
        /// </summary>
        /// <param name="jobnumber">工号</param>
        /// <returns></returns>
        public UserModel GetDingTalkUserModel(string jobnumber)
        {
            try
            {
                var userModel = db.Queryable<Model.MesDb.t_DD_UserDetail>().Where(it => it.jobnumber == jobnumber && it.companyName == "重庆盟讯电子科技有限公司").First();
                if (userModel == null)
                {
                    return null;
                }
                return new UserModel() { userName = jobnumber, nickName = userModel.username, bumen = userModel.workPlace, zhiwei = userModel.position };
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取Erp人员信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public UserModel GetErpUserModel(string userId)
        {
            try
            {
                Model.MesDb.CAP_USER userModel = db.Queryable<Model.MesDb.CAP_USER>().Where(it => it.USER_ID == userId).First();
                if (userModel == null)
                {
                    return null;
                }
                return new UserModel() { userName = userId, nickName = userModel.USER_NAME };
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Mes登录接口
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="passWord"></param>
        /// <returns></returns>
        public bool Login(string userId, string passWord,bool login =true)
        {
            try
            {
                if (true)
                {
                    string serviceAddress = "http://192.168.2.2:8080/default/org.gocom.components.coframe.auth.LoginManager.loginUserDefineWMS.biz.ext?userId=" + userId + "&password=" + passWord + "&role=1";
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
                    request.Method = "GET";
                    request.ContentType = "text/html;charset=UTF-8";
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    Stream myResponseStream = response.GetResponseStream();
                    StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                    string retString = myStreamReader.ReadToEnd();
                    myStreamReader.Close();
                    myResponseStream.Close();
                    string userFlag = retString.Substring(retString.IndexOf(":") + 1, 1);
                    string passFlsg = retString.Substring(retString.IndexOf("retCode") + 9, 1);
                    if (userFlag != "1" || passFlsg != "1")
                    {
                        return false;
                    }
                    return true;
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static UserModel GetUserName(string id, ref string errMsg, string url = "")
        {
            try
            {
                string getUserNameGetURL = url == "" ? "http://192.168.2.23:9220/stationDetect/login/findByUserName?userName=" : url;
                string result = HttpHelper.Get(getUserNameGetURL + id);
                HttpModel.GetUserRb resultModel = JsonConvert.DeserializeObject<HttpModel.GetUserRb>(result);
                if (resultModel.code != 200)
                {
                    errMsg = resultModel.message;
                    return null;
                }
                UserModel user = JsonConvert.DeserializeObject<UserModel>(resultModel.data.ToString());
                return user;
            }
            catch (Exception ex)
            {
                errMsg = "接口调用失败";
                return null;
            }
        }

        public static UserModel Login(string id, string password, ref string errMsg)
        {
            try
            {
                string getUserNameGetURL = "http://192.168.2.23:9213/integrate/login/queryGenerLogin";
                Newtonsoft.Json.Linq.JObject postObj = new Newtonsoft.Json.Linq.JObject
                                                       {
                                                        { "uername", id },
                                                        { "password", password },
                                                      };
                string result = HttpHelper.Post(getUserNameGetURL,JsonConvert.SerializeObject(postObj));
                HttpModel.GetUserRb resultModel = JsonConvert.DeserializeObject<HttpModel.GetUserRb>(result);
                if (resultModel.code != 200)
                {
                    errMsg = resultModel.msg;
                    return null;
                }
                UserModel user = JsonConvert.DeserializeObject<UserModel>(resultModel.data.ToString());
                return user;
            }
            catch (Exception ex)
            {
                errMsg = "接口调用失败";
                return null;
            }
        }

        public static bool SendMsg(string msg, ref string errMsg, List<string> id)
        {
            try
            {
                List<string> list = new List<string>();
                foreach (var item in id)
                {
                    if (list.Contains(item) == false)
                    {
                        list.Add(item);
                    }
                }
                string ids = string.Join(",", list);
                string url = "http://192.168.2.23:9213/integrate/cmccMonitor/rateAlertByCMCC?";
                string get = $"context={msg}&messageType=软件管理平台&username={ids}";
                string result = HttpHelper.Get(url +get);
                HttpModel.GetUserRb resultModel = JsonConvert.DeserializeObject<HttpModel.GetUserRb>(result);
                if (resultModel.code != 200)
                {
                    errMsg = resultModel.msg;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                errMsg = "接口调用失败";
                return false;
            }
        }
    }
}
